home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c
- Path: link-1.ts.bcc.ac.uk!reavpar
- From: reavpar@ucl.ac.uk (Mr Philip Arthur Riebold)
- Subject: Re: How to get a random string each time??
- Message-ID: <1996Feb21.150754.81848@ucl.ac.uk>
- Date: Wed, 21 Feb 1996 15:07:54 GMT
- References: <4fh5od$qq0@news.nevada.edu> <4g4c5m$tlb@news.nevada.edu>
- Organization: University College London
-
- chancl@nevada.edu (Clapton Chan) writes:
-
- >Thanks for all of you kind C gurus. My problem is solved.
- >I did make some stupid code earlier, but hey, everyone gives
- >the new guy a break, right?
-
- >I now post my solution for your comments.
-
- >**************Here*is*the*question*********************
-
- >Write a program that reads the list of strings and then selects
- >and prints a random string from the list.
-
- >*************Here*is*my*solution***********************
-
- >#include <stdio.h>
- >#include <string.h>
- >#include <stdlib.h> /* This is where srand and rand is located.*/
- >
- > int main ()
- > {
- > char *p, str[10][80];
- > int i, j;
- >
- > srand(time(NULL)); /* pseudocode */
- > printf("Enter 10 strings (or '999' to quit):\n");
- > for(i=0; i<10; i++) {
- > fgets(str[i], sizeof(str[i]), stdin);
- > if((p=strchr(str[i], '\n')) != NULL) *p='\0';
- > if(!(strcmp(str[i], "999")))
- > break;
- > }
- >
- > j = rand();
- > j = j%i; /* this handles early program exit */
- > printf("\nAnswer: %s\n", str[j]);
- >
- > return 1;
- > }
-
- >*************************End******************************
-
- >I hope this program is bug-less. ;)
-
- >Cheers,
- >Clapton
- >http://www.nevada.edu/home/15/chancl/html/homepage.html
-
- Alternatively to save having to buffer each line try this :-
-
- int main(void)
- {
- char line[BUFSIZ], it[BUFSIZ];
- int n;
- srand48(time(NULL)); /* or seed the generator in some other way */
- for(n = 1; gets(line); n++) /*probably better to use fgets()*/
- if((n * drand48()) < 1.0) /*drand returns a double in [0.0, 1.0) */
- strcpy(it, line);
- puts(it);
- }
-
- --
- Philip Riebold,
-
-